// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package task

import (
	"context"
	"crypto/tls"
	"fmt"

	"github.com/kumose/errors"
	operator "github.com/kumose/kmopt/pkg/cluster/operation"
	"github.com/kumose/kmopt/pkg/cluster/spec"
)

// ClusterOperate represents the cluster operation task.
type ClusterOperate struct {
	spec    *spec.Specification
	op      operator.Operation
	options operator.Options
	tlsCfg  *tls.Config
}

// Execute implements the Task interface
func (c *ClusterOperate) Execute(ctx context.Context) error {
	var (
		err error
	)
	var opErrMsg = [...]string{
		"failed to start",
		"failed to stop",
		"failed to restart",
		"failed to destroy",
		"failed to upgrade",
		"failed to scale in",
		"failed to scale out",
		"failed to destroy tombstone",
	}
	switch c.op {
	case operator.ScaleInOperation:
		err = operator.ScaleIn(ctx, c.spec, c.options, c.tlsCfg)
		// printStatus = false
	case operator.DestroyTombstoneOperation:
		_, err = operator.DestroyTombstone(ctx, c.spec, false, c.options, c.tlsCfg)
	default:
		return errors.Errorf("nonsupport %s", c.op)
	}

	if err != nil {
		return errors.Annotatef(err, "%s", opErrMsg[c.op])
	}

	return nil
}

// Rollback implements the Task interface
func (c *ClusterOperate) Rollback(ctx context.Context) error {
	return ErrUnsupportedRollback
}

// String implements the fmt.Stringer interface
func (c *ClusterOperate) String() string {
	return fmt.Sprintf("ClusterOperate: operation=%s, options=%+v", c.op, c.options)
}
